package com.person.consumer.lb.myirule;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyRule implements MyRuleInterface {

    private AtomicInteger atomicInteger = new AtomicInteger(0);//原子性初始化
    @Resource
    DiscoveryClient discoveryClient;

    public int getAtomicTnteger() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }
        while (!this.atomicInteger.compareAndSet(current, next));
        return next;
    }

    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int next = getAtomicTnteger();

        int size = serviceInstances.size();

        int mark = next % size;


        return serviceInstances.get(mark);
    }
}
